package com.ganyu.handler.security;

import com.alibaba.fastjson.JSON;
import com.ganyu.domain.ResponseResult;
import com.ganyu.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.ganyu.enums.AppHttpCodeEnum.*;

/**
 * DATA: 2022/9/15
 * Author: 晨夕
 * @Description 认证失败异常处理器
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //BadCredentialsException 登录失败
        //InsufficientAuthenticationException 无权限
        ResponseResult responseResult = null;
        if(e instanceof BadCredentialsException){
            //用户名错误
            responseResult = ResponseResult.errorResult(LOGIN_ERROR.getCode(),e.getMessage());
        }else if(e instanceof InsufficientAuthenticationException){
            //无权限
            responseResult = ResponseResult.errorResult(NEED_LOGIN);
        }else {
            //出现其他错误
            responseResult = ResponseResult.errorResult(SYSTEM_ERROR.getCode(),"认证或授权失败");
        }
        //响应给前端
        WebUtils.renderString(httpServletResponse, JSON.toJSONString(responseResult));
    }
}
